package com.icesoft.base.manager.base;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icesoft.core.common.exception.CheckException;
import com.icesoft.core.common.exception.CodeErrorException;
import com.icesoft.core.web.helper.excel.ExcelUtil;
import com.icesoft.core.web.helper.excel.ExcelUtil.CellHandle;

/**
 * @author XHH
 */
public abstract class BaseExportAction<T> {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());

	/**
	 * 指定表头
	 */
	protected abstract String[] getExcelHead();

	/**
	 * bean转成excel行数据
	 * 
	 * @param model
	 *            要导出的bean对象
	 * @return excel行数据
	 */
	protected abstract String[] convert(T model);

	public final List<Map<String, String>> toMaps(List<T> models) {
		List<Map<String, String>> data = new ArrayList<>();
		String[] excelHead = getExcelHead();
		if (models == null || models.isEmpty()) {
			LinkedHashMap<String, String> map = new LinkedHashMap<>();
			for (int i = 0; i < excelHead.length; i++) {
				map.put(excelHead[i], " ");
			}
			data.add(map);
			return data;
		}
		models.forEach(model -> {
			String[] list = convert(model);
			if (list.length != excelHead.length) {
				throw new CodeErrorException("导出数据长度与表头长度不一致，请检查代码");
			}
			LinkedHashMap<String, String> map = new LinkedHashMap<>();
			for (int i = 0; i < excelHead.length; i++) {
				map.put(excelHead[i], list[i]);
			}
			data.add(map);
		});
		if (log.isTraceEnabled()) {
			log.trace("导出数据：{}", data);
		}
		return data;
	}

	public CellHandle cellHandle() {
		return new CellHandle();
	}

	public final void writeToExcel(List<Map<String, String>> data, String pathAndName) {
		try {
			ExcelUtil.writeToExcel(data, pathAndName, cellHandle());
		} catch (IOException e) {
			log.error("写excel失败", e);
			throw new CheckException("写excel失败：" + e.getMessage());
		}
	}

}
